package cn.fcq.org.service.impl;

import cn.fcq.basic.exception.BusinessException;
import cn.fcq.basic.util.BaiduAuditUtils;
import cn.fcq.basic.util.ExcelUtil;
import cn.fcq.org.domain.Employee;
import cn.fcq.org.domain.Shop;
import cn.fcq.org.domain.ShopAuditLog;
import cn.fcq.org.mapper.EmployeeMapper;
import cn.fcq.org.mapper.ShopAuditLogMapper;
import cn.fcq.org.mapper.ShopMapper;
import cn.fcq.org.service.IShopService;
import cn.fcq.basic.service.impl.BaseServiceImpl;
import cn.fcq.org.vo.ShopVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xuchao
 * @since 2022-06-12
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;

    @Autowired
    private JavaMailSender javaMailSender;
    /**
     * 店铺入驻
     * 一：参数空校验
     *      不能为空
     * 二：合法校验   @TODO 百度AI智能审核接口做
     * 三：判断是否曾经已经注册过
     *     1. 店铺不能被注册
     *     2.人是否被注册
     *       2.1 注册了但是没有绑定店铺
     *       2.2 注册了并且已经绑定了店铺
     * 四：保存数据
     *     shop
     *     employee  shopId
     *     反过来修改shop中的admin_id
     */

    public void settlement(Shop shop){
        Employee admin = shop.getAdmin();
//      一：参数空校验
        if(StringUtils.isEmpty(shop.getName())
                || StringUtils.isEmpty(shop.getAddress())
                || StringUtils.isEmpty(admin.getUsername())
        ){
            throw new BusinessException("亲，参数不能为空哦！");
        }
//       不能为空
//      二：合法校验
        //1.验证店铺名称或者验证账户
        if(!BaiduAuditUtils.TextCensor(shop.getName())){
            throw new BusinessException("小伙子,单纯一点！！要学好");
        }
//      三：判断是否曾经已经注册过
        Shop shopTmp = shopMapper.loadByName(shop.getName());
//        *    1. 店铺不能被注册
        if(shopTmp != null){
            throw new BusinessException("店铺已注册，请直接登录！！！");
        }
//        *    2.人是否被注册
        Employee empTmp = employeeMapper.loadByUsername(admin.getUsername());
        if(empTmp != null && empTmp.getShop_id() != null){
//        *      2.2 注册了并且已经绑定了店铺
            throw new BusinessException("该用户已绑定店铺，请重新换人！！");
        }
//        *      2.1 注册了但是没有绑定店铺  === 直接绑定
        if(empTmp == null){
            employeeMapper.save(admin);//要返回自增ID
            empTmp = admin;
        }
        //  empTmp 一定有值
//        *  四：保存数据
//        *    shop
        shop.setAdminId(empTmp.getId());
        shopMapper.save(shop);//返回自增ID
//       employee  shopId
//       反过来修改shop中的admin_id
        empTmp.setShop_id(shop.getId());
        employeeMapper.update(empTmp);
    }

    /**
     * 店铺驳回
     * @param log
     */
    @Override
    public void reject(ShopAuditLog log) {
        //1.修改店铺状态为驳回
        Shop shop = shopMapper.loadById(log.getShopId());
        shop.setState(-1);//-1状态码为驳回
        //再把状态赋值给店铺状态
        shopMapper.update(shop);
        System.out.println(shop);
        // 2.记录日志
        log.setAuditId(334L);
        log.setState(-1);
        shopAuditLogMapper.save(log);
        System.out.println(log);
        //3.发送修改链接
        //给店铺管理员发送信息
        Employee employee = employeeMapper.loadById(shop.getAdminId());
        System.out.println(employee);
        System.out.println(shop.getAdminId());
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        //设置发送人
        mailMessage.setFrom("2668374470@qq.com");
        //邮件主题
        mailMessage.setSubject("宠物乐园，店铺注册！！");
        //邮件内容
        mailMessage.setText("亲，您的店铺注册失败，请点击链接修改相关信息重新注册哦！"+"http://localhost:8081/#/register2?shopId="+log.getShopId());
        //收件人
        mailMessage.setTo(employee.getEmail());
        System.out.println(employee.getEmail());

        javaMailSender.send(mailMessage);

    }

    /**
     * 店铺通过
     * @param log
     */
    @Override
    public void pass(ShopAuditLog log) {
        //1.修改店铺状态为通过
        Shop shop = shopMapper.loadById(log.getShopId());
        shop.setState(1);
        shopMapper.update(shop);
        //2.记录日志
        log.setAuditId(333L);
        log.setState(1);
        shopAuditLogMapper.save(log);
        //3.发送通过邮件激活链接
        Employee employee = employeeMapper.loadById(shop.getAdminId());
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        //设置发送人
        mailMessage.setFrom("2668374470@qq.com");
        //邮件主题
        mailMessage.setSubject("宠物乐园，店铺注册！！");
        //邮件内容
        mailMessage.setText("亲，您的店铺注册成功，请尽快点击激活链接激活哦！"+"http://localhost:8080/shop/activation/"+log.getShopId());
        //收件人
        mailMessage.setTo(employee.getEmail());

        javaMailSender.send(mailMessage);
    }

    /**
     * 店铺激活
     * @param id
     */
    @Override
    public void activation(Long id) {
        Shop shop = shopMapper.loadById(id);
        shop.setState(4);
        shopMapper.update(shop);

    }

    @Override
    public Map<String, Object> getEcharts() {
        List<ShopVo> echarts = shopMapper.getEcharts();
        //所有状态分类数据
        List<String> states = new ArrayList<>();
        for (ShopVo echart : echarts) {
            states.add(echart.getState());
        }
        //所有次数数据
        List<Integer> counts = new ArrayList<>();
        for (ShopVo echart : echarts) {
            counts.add(echart.getCount());
        }
        //封装为map集合
        Map<String, Object> map = new HashMap<>();
        map.put("x",states);
        map.put("y",counts);
        return map;
    }

    /**
     * 导入
     * @param file
     */
    @Override
    public void importExcel(MultipartFile file) {
        List<Shop> shops = ExcelUtil.importExcel(file, 0, 1, Shop.class);
        for (Shop shop : shops) {
            String state = shop.getStateCn();
            switch (state){
                case "审核通过": shop.setState(1); break;
                case "待审核": shop.setState(0); break;
                case "拒绝": shop.setState(-1); break;
                case "驳回": shop.setState(2); break;
                case "待激活": shop.setState(3); break;
                case "已激活": shop.setState(4); break;
                default: shop.setState(5); break;
            }
        }
        batchInsert(shops);

    }

    public void batchInsert(List<Shop> shops) {
        for (Shop shop : shops) {
            shopMapper.save(shop);
        }
    }

    /**
     * 导出
     * @param response
     */
    @Override
    public void exportExcel(HttpServletResponse response) {
        List<Shop> shops = shopMapper.loadAll();
        for (Shop shop : shops) {
            Integer state = shop.getState();
            switch (state){
                case 1: shop.setStateCn("审核通过"); break;
                case 0: shop.setStateCn("待审核"); break;
                case -1: shop.setStateCn("驳回"); break;
                case 2: shop.setStateCn("拒绝"); break;
                case 3: shop.setStateCn("待激活"); break;
                case 4: shop.setStateCn("已激活"); break;
                default: shop.setStateCn("未知"); break;
            }
        }

        ExcelUtil.exportExcel(shops,null,
                "店铺报表",
                Shop.class,
                "店铺报表.xls",
                response);

    }

}
